package com.eight.cloud.rabbitmq.util;

/**
 * 令牌桶速率限制器
 *
 * @ClassName: RateLimiter
 * @Author: TXC
 * @Date: 2025-08-13 16:10
 **/
public class RateLimiter {
    private final double permitsPerSecond;
    private long lastAcquireTime = System.nanoTime();
    private double availablePermits;

    public RateLimiter(double permitsPerSecond) {
        this.permitsPerSecond = permitsPerSecond;
        this.availablePermits = permitsPerSecond;
    }

    public synchronized boolean tryAcquire() {
        refillPermits();
        if (availablePermits >= 1) {
            availablePermits -= 1;
            return true;
        }
        return false;
    }

    private void refillPermits() {
        long now = System.nanoTime();
        double elapsedSeconds = (now - lastAcquireTime) / 1_000_000_000.0;
        double newPermits = elapsedSeconds * permitsPerSecond;

        availablePermits = Math.min(permitsPerSecond, availablePermits + newPermits);
        lastAcquireTime = now;
    }
}
